package com.jinxin.platform.cdysylives.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdysylives.bean.bo.AppKeySecretInfo;
import com.jinxin.platform.cdysylives.bean.bo.DataResult;
import com.jinxin.platform.cdysylives.bean.bo.DataResult2;
import com.jinxin.platform.cdysylives.bean.bo.DeviceInfo;
import com.jinxin.platform.cdysylives.common.CommonCodeEntity;
import com.jinxin.platform.cdysylives.common.Constant;
import com.jinxin.platform.cdysylives.common.ResultEntity;
import com.jinxin.platform.cdysylives.redis.RedisUtil;
import com.jinxin.platform.cdysylives.service.IEquipmentService;
import com.jinxin.platform.cdysylives.utils.HttpClientPoolUtil;
import com.jinxin.platform.cdysylives.utils.HttpClientResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class IEquipmentServiceImpl implements IEquipmentService {
    @Autowired
    private RedisUtil redisUtil;
    @Value("${cdysylives.api-url.get-token}")
    private String tokenUrl;
    @Value("${cdysylives.api-url.get-address}")
    private String addressUrl;
    @Value("${cdysylives.api-url.list-video}")
    private String videoUrl;
    @Value("${cdysylives.api-url.list-device}")
    private String deviceUrl;

    private ResultEntity getToken(){
//        String tokenKey = Constant.YSY_ACCESS_TOKEN;
//        if(redisUtil.hasKey(tokenKey)){
//            return new ResultEntity(CommonCodeEntity.SUC_CODE,"获取token成功",redisUtil.get(tokenKey));
//        }
        String jsonStr = (String)redisUtil.get(Constant.YSY_APPKEY_SECRET);
        if(StringUtils.isEmpty(jsonStr)){
            return new ResultEntity(CommonCodeEntity.FAIL,"未配置应用秘钥信息，获取token失败",null);
        }
        AppKeySecretInfo keySecretInfo = JSONObject.parseObject(jsonStr, AppKeySecretInfo.class);
        if(keySecretInfo == null){
            return new ResultEntity(CommonCodeEntity.FAIL,"获取应用秘钥信息失败",null);
        }
        Map<String,String> params = new HashMap<>();
        params.put("appKey",keySecretInfo.getAppKey());
        params.put("appSecret",keySecretInfo.getSecret());
        try {
            HttpClientResult clientResult = HttpClientPoolUtil.doPost(tokenUrl, params, true);
            if(Constant.REQUEST_STATUS_SUCCEED.equals(clientResult.getCode())){
                DataResult response = JSON.parseObject(clientResult.getContent(), DataResult.class);
                JSONObject jsonObject = response.getData();
                if(jsonObject != null){
                    String accessToken = jsonObject.getString("accessToken");
                    Long expireTime = jsonObject.getLong("expireTime");// 具体过期时间，精确到毫秒
                    long time = expireTime > 0 ? (expireTime - System.currentTimeMillis())/1000 : 0;
                    ///redisUtil.set(tokenKey,accessToken,time);//单位是秒
                    return new ResultEntity(CommonCodeEntity.SUC_CODE,"获取token成功",accessToken);
                }

            }
            return new ResultEntity(CommonCodeEntity.FAIL,"请求失败",null);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return new ResultEntity(CommonCodeEntity.FAIL,"获取token失败",null);
    }

    @Override
    public Map<String, Object> listDevices() {
        Map<String,Object> resultMap = new HashMap<>();
        ResultEntity tokenEntity = getToken();
        if(CommonCodeEntity.FAIL.equals(tokenEntity.getResultCode())){
            resultMap.put("code",CommonCodeEntity.FAIL);
            resultMap.put("msg",tokenEntity.getResultDesc());
            return resultMap;
        }
        Map<String, String> params =new HashMap<>();
        params.put("accessToken", (String) tokenEntity.getResultContent());
        // 个人版设备接入上限：10台，无分页功能；如需更完善的功能,请升级为企业版
        params.put("pageStart", "0");
        params.put("pageSize", "50"); //默认为10，最大为50
        int count = 0;
        List<DeviceInfo> data = new ArrayList<>();
        try {
            HttpClientResult clientResult = HttpClientPoolUtil.doPost(deviceUrl, params, true);
            if(Constant.REQUEST_STATUS_SUCCEED.equals(clientResult.getCode())){
                DataResult2 response = JSON.parseObject(clientResult.getContent(), DataResult2.class);
                if(response == null || !"200".equals(response.getCode())){
                    resultMap.put("code",CommonCodeEntity.FAIL);
                    resultMap.put("msg",response.getMsg());
                    return resultMap;
                }
                JSONObject pageJson = response.getPage();
                if(pageJson != null){
                    count = pageJson.getInteger("total");
                }
//                JSONArray jsonArray = response.getData();
                data = JSON.parseArray(response.getData(), DeviceInfo.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultMap.put("code",0);
        resultMap.put("msg","success");
        resultMap.put("count",count);
        resultMap.put("data",data);
        return resultMap;
    }

    @Override
    public ResultEntity getVideoAddress(String deviceSerial,String quality) {
        if(StringUtils.isEmpty(deviceSerial)){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"直播源不存在",null);
        }
        if(StringUtils.isEmpty(quality)){
            quality = "2";
        }
        ResultEntity tokenEntity = getToken();
        if(CommonCodeEntity.FAIL.equals(tokenEntity.getResultCode())){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,tokenEntity.getResultDesc(),null);
        }
        Map<String,String> params = new HashMap<>();
        String token = (String) tokenEntity.getResultContent();
        params.put("accessToken", token);
        params.put("deviceSerial",deviceSerial);
        params.put("quality",quality); //1高清2流畅
        try {
            HttpClientResult clientResult = HttpClientPoolUtil.doPost(addressUrl, params, true);
            if(Constant.REQUEST_STATUS_SUCCEED.equals(clientResult.getCode())){
                DataResult response = JSON.parseObject(clientResult.getContent(), DataResult.class);
                JSONObject jsonObject = response.getData();
                if(jsonObject != null){
                    String url = jsonObject.getString("url");
                    Map<String,String> resultMap = new HashMap<>();
                    resultMap.put("token", token);
                    resultMap.put("url",url);
                    return new ResultEntity(CommonCodeEntity.SUC_CODE,"获取播放地址成功",resultMap);
                }
            }
            return new ResultEntity(CommonCodeEntity.FAIL,"请求失败",null);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return new ResultEntity(CommonCodeEntity.FAIL,"获取播放地址失败",null);
    }
}
